import { ElMessage, ElNotification, ElMessageBox } from 'element-plus'
import { apiTestUtil, checkDatabaseConnection, initializeTestData } from '@/utils/apiTest'
import { get, post } from '@/utils/request'

// 后端对接初始化工具
export class BackendInitializer {
  constructor() {
    this.initSteps = [
      { name: '检查后端服务', handler: this.checkBackendService },
      { name: '验证数据库连接', handler: this.checkDatabase },
      { name: '检查API接口', handler: this.checkApiEndpoints },
      { name: '验证认证系统', handler: this.checkAuthSystem },
      { name: '初始化基础数据', handler: this.initializeData },
      { name: '验证业务功能', handler: this.checkBusinessFunctions }
    ]
    this.currentStep = 0
    this.isInitializing = false
  }

  // 开始后端对接初始化
  async startInitialization() {
    if (this.isInitializing) {
      ElMessage.warning('正在初始化中，请稍候...')
      return
    }

    try {
      const confirmed = await ElMessageBox.confirm(
        '即将开始后端对接初始化，这将检查所有必要的服务和数据。是否继续？',
        '后端对接初始化',
        {
          confirmButtonText: '开始初始化',
          cancelButtonText: '取消',
          type: 'info'
        }
      )

      if (!confirmed) return

      this.isInitializing = true
      this.currentStep = 0

      ElNotification({
        title: '后端对接初始化',
        message: '开始初始化后端对接...',
        type: 'info',
        duration: 3000
      })

      // 执行初始化步骤
      for (let i = 0; i < this.initSteps.length; i++) {
        this.currentStep = i
        const step = this.initSteps[i]
        
        ElNotification({
          title: `步骤 ${i + 1}/${this.initSteps.length}`,
          message: step.name,
          type: 'info',
          duration: 2000
        })

        try {
          await step.handler.call(this)
          console.log(`✅ ${step.name} - 完成`)
        } catch (error) {
          console.error(`❌ ${step.name} - 失败:`, error)
          throw new Error(`${step.name}失败: ${error.message}`)
        }
      }

      // 初始化完成
      ElNotification({
        title: '后端对接初始化完成',
        message: '所有步骤已成功完成，系统已准备就绪！',
        type: 'success',
        duration: 5000
      })

      return true

    } catch (error) {
      console.error('后端对接初始化失败:', error)
      ElNotification({
        title: '初始化失败',
        message: error.message || '后端对接初始化失败',
        type: 'error',
        duration: 8000
      })
      return false
    } finally {
      this.isInitializing = false
    }
  }

  // 检查后端服务
  async checkBackendService() {
    try {
      const response = await get('/health', {}, {
        showError: false,
        showLoading: false,
        timeout: 10000
      })

      if (response.code === 200) {
        console.log('后端服务状态:', response.data)
        return true
      } else {
        throw new Error('后端服务响应异常')
      }
    } catch (error) {
      throw new Error('无法连接到后端服务，请确保Spring Boot应用已启动')
    }
  }

  // 检查数据库连接
  async checkDatabase() {
    const isConnected = await checkDatabaseConnection()
    if (!isConnected) {
      throw new Error('数据库连接失败，请检查MySQL服务和配置')
    }
    return true
  }

  // 检查API接口
  async checkApiEndpoints() {
    await apiTestUtil.testApiConnection()
    const results = apiTestUtil.getTestResults()
    const successCount = results.filter(r => r.success).length
    const totalCount = results.length
    
    if (successCount < totalCount * 0.7) {
      throw new Error(`API接口测试失败，仅 ${successCount}/${totalCount} 个接口可用`)
    }
    
    return true
  }

  // 检查认证系统
  async checkAuthSystem() {
    try {
      // 测试登录接口
      const loginResponse = await post('/auth/login', {
        username: 'test',
        password: 'test'
      }, {
        showError: false,
        showLoading: false,
        timeout: 5000
      })

      // 即使登录失败，只要接口存在就算成功
      console.log('认证系统检查完成')
      return true
    } catch (error) {
      // 401错误是正常的，说明认证系统工作正常
      if (error.response?.status === 401 || error.code === 401) {
        return true
      }
      throw new Error('认证系统不可用')
    }
  }

  // 初始化基础数据
  async initializeData() {
    try {
      // 检查是否需要初始化数据
      const checkResponse = await get('/system/data-status', {}, {
        showError: false,
        showLoading: false,
        timeout: 5000
      })

      if (checkResponse.code === 200 && checkResponse.data.initialized) {
        console.log('基础数据已存在，跳过初始化')
        return true
      }

      // 初始化测试数据
      const initialized = await initializeTestData()
      if (!initialized) {
        throw new Error('基础数据初始化失败')
      }

      return true
    } catch (error) {
      // 如果接口不存在，跳过这一步
      if (error.response?.status === 404) {
        console.log('数据初始化接口不存在，跳过此步骤')
        return true
      }
      throw error
    }
  }

  // 验证业务功能
  async checkBusinessFunctions() {
    const businessChecks = [
      { name: '仪表板数据', endpoint: '/dashboard/overview' },
      { name: '订单管理', endpoint: '/orders' },
      { name: '服务管理', endpoint: '/services' },
      { name: '财务管理', endpoint: '/finance/overview' }
    ]

    let successCount = 0
    for (const check of businessChecks) {
      try {
        await get(check.endpoint, {}, {
          showError: false,
          showLoading: false,
          timeout: 5000
        })
        successCount++
      } catch (error) {
        // 401错误是正常的，说明接口存在但需要认证
        if (error.response?.status === 401 || error.code === 401) {
          successCount++
        }
      }
    }

    if (successCount < businessChecks.length * 0.8) {
      throw new Error(`业务功能检查失败，仅 ${successCount}/${businessChecks.length} 个功能可用`)
    }

    return true
  }

  // 获取初始化进度
  getProgress() {
    return {
      current: this.currentStep,
      total: this.initSteps.length,
      percentage: Math.round((this.currentStep / this.initSteps.length) * 100)
    }
  }

  // 获取当前步骤
  getCurrentStep() {
    return this.initSteps[this.currentStep]?.name || '未知步骤'
  }
}

// 创建全局实例
export const backendInitializer = new BackendInitializer()

// 快速检查后端连接状态
export async function quickCheckBackend() {
  try {
    const response = await get('/health', {}, {
      showError: false,
      showLoading: false,
      timeout: 3000
    })

    return {
      connected: true,
      status: response.data?.status || 'unknown',
      message: '后端服务连接正常'
    }
  } catch (error) {
    return {
      connected: false,
      status: 'error',
      message: error.message || '无法连接到后端服务'
    }
  }
}

// 检查必要的环境变量
export function checkEnvironmentConfig() {
  const requiredEnvVars = [
    'VITE_APP_BASE_API',
    'VITE_APP_TITLE',
    'VITE_APP_ENV'
  ]

  const missingVars = []
  const config = {}

  requiredEnvVars.forEach(varName => {
    const value = import.meta.env[varName]
    if (!value) {
      missingVars.push(varName)
    } else {
      config[varName] = value
    }
  })

  return {
    valid: missingVars.length === 0,
    missingVars,
    config
  }
}

// 显示后端连接状态
export async function showBackendStatus() {
  const envCheck = checkEnvironmentConfig()
  const backendCheck = await quickCheckBackend()

  let message = '后端连接状态检查:\n\n'
  
  // 环境配置检查
  message += `环境配置: ${envCheck.valid ? '✅ 正常' : '❌ 缺少配置'}\n`
  if (!envCheck.valid) {
    message += `缺少配置: ${envCheck.missingVars.join(', ')}\n`
  }
  message += `API地址: ${envCheck.config.VITE_APP_BASE_API || '未配置'}\n\n`

  // 后端连接检查
  message += `后端连接: ${backendCheck.connected ? '✅ 正常' : '❌ 失败'}\n`
  message += `状态信息: ${backendCheck.message}\n`

  ElMessageBox.alert(message, '后端连接状态', {
    confirmButtonText: '确定',
    type: backendCheck.connected && envCheck.valid ? 'success' : 'warning'
  })
}
